package com.kasax.httpclient.interceptors;

import com.kasax.httpclient.HttpUrl;
import com.kasax.httpclient.beans.Request;
import com.kasax.httpclient.beans.Response;
import com.kasax.httpclient.core.HttpConnection;
import com.kasax.httpclient.core.KOkHttpClient;
import com.kasax.httpclient.core.inters.Interceptor;
import com.kasax.httpclient.utils.LogUtils;

import java.io.IOException;

public class ConnectionInterceptor implements Interceptor {


    @Override
    public Response intercpt(Chain chain) throws IOException {
        LogUtils.i(getClass(), "intercpt");
        Request request = chain.call().request();
        KOkHttpClient okHttpClient = chain.call().client();
        HttpUrl httpUrl = request.url();
        String host = httpUrl.getHost();
        int port = httpUrl.getPort();
        HttpConnection httpConnection = okHttpClient.connectionPool().get(host, port);
        if (httpConnection == null) {
            LogUtils.i(getClass(), "构建新的httpconnection");
            httpConnection = new HttpConnection();
        } else {
            LogUtils.i(getClass(), "使用连接池中的对象");
        }
        httpConnection.setRequest(request);
        LogUtils.i(getClass(), "使用连接池中的对象");
        try {
            Response response = chain.procced(httpConnection);
            if (response != null) {
                if (response.isKeepAlive()) {
                    // 长连接
                    okHttpClient.connectionPool().put(httpConnection);
                }
                return response;
            } else {
                throw new IOException("response is null");
            }
        } catch (IOException e) {
            throw new IOException(e);
        }
    }
}
